package com.sskj.level.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.BuySellEnum;
import com.sskj.level.bean.TradeListBean;
import com.sskj.level.bean.WinLossBean;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.HolderFragmentPresenter;
import com.sskj.level.util.TipLevelUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.mvchelper.RefreshDataSource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.LEVEL_FRAGMENT_HOLDER)//持仓
public class HolderFragment extends BaseFragment<HolderFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private SlimAdapter<TradeListBean> slimAdapter;
    private int curPos;
    private MVCCoolHelper<List<TradeListBean>> mvcCoolHelper;
    private MaterialDialog setTip;
    private Disposable subscribe;
    @Inject
    UserViewModel userViewModel;

    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_holder;
    }

    @Override
    public HolderFragmentPresenter getPresenter() {
        return new HolderFragmentPresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden && mvcCoolHelper != null) {
            mvcCoolHelper.refresh();
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        slimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_holder, new SlimInjector<TradeListBean>() {
            @Override
            public void onInject(TradeListBean data, IViewInjector injector, List payloads) {
                injector
                        .textColor(R.id.tv_mm, ContextCompat.getColor(App.INSTANCE, data.getOtype().equals(BuySellEnum.BUY.getType()) ? BuySellEnum.BUY.getColorRes() : BuySellEnum.SELL.getColorRes()))
                        .text(R.id.tv_mm, data.getOtype().equals(BuySellEnum.BUY.getType()) ? BuySellEnum.BUY.getTitle() : BuySellEnum.SELL.getTitle())//买入卖出
                        .text(R.id.tv_bz, data.getPname())//币种类型
                        .text(R.id.tv_time, data.getAddtime())//时间
                        .text(R.id.tv_first_left, data.getMarketLimit())//类型
                        .text(R.id.level_fd_type, App.INSTANCE.getString(R.string.levelJavaHolderFragment1) + data.getFdyk())//盈亏
                        .text(R.id.tv_first_right, data.getLeverage())//杠杆倍数
                        .text(R.id.tv_second_left, data.getBuyprice())//持仓价
                        .text(R.id.tv_second_right, data.getNewprice())//最新价
                        .text(R.id.tv_third_left, data.getBuynum())//数量
                        .text(R.id.tv_third_right, data.getDayfee())//过夜费
                        .text(R.id.tv_four_left, data.getSxfee())//手续费
                        .text(R.id.tv_four_right, data.getTotalprice())//保证金
                        .text(R.id.tv_five_left, data.getStopwin())//止盈价
                        .text(R.id.tv_five_right, data.getStoploss())//止损价
                        .background(R.id.level_fd_type,ContextCompat.getDrawable(App.INSTANCE,Double.valueOf(data.getFdyk())>0?R.drawable.level_shape_green2:R.drawable.level_shape_red2))

                        .clicked(R.id.tvPingCang, v -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            pingCang();
                        })
                        .clicked(R.id.tvSet, v -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            mPresenter.getWinLoss(data.getPid());
                        });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        RefreshDataSource<TradeListBean> refreshDataSource = new RefreshDataSource<TradeListBean>(coolRefreshView) {
            @Override
            public Flowable<List<TradeListBean>> loadData() {
                return mPresenter.getTradeListFlow();
            }
        };
        mvcCoolHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcCoolHelper.setDataSource(refreshDataSource);
        mvcCoolHelper.setAdapter(slimAdapter);
        mvcCoolHelper.refresh();
        startTimer();

    }

    public void updateUI(List<TradeListBean> data) {

        if (data == null || data.size() == 0) {
            RxBus.getDefault().send(RxBusCode.ALL_PINGCANG_DISMISS);
        } else {
            RxBus.getDefault().send(RxBusCode.ALL_PINGCANG_SHOW);

        }
        if (slimAdapter != null) {
            if (data.size() > 0 && slimAdapter.getData().size() == 0) {
                mvcCoolHelper.refresh();
            }
            slimAdapter.updateData(data);
        }
    }


    public void refresh() {
        if (mPresenter != null) {
            mPresenter.getTradeList();
        }
    }


    /**
     * 平仓
     */
    private void pingCang() {
        TradeListBean dataItem = slimAdapter.getDataItem(curPos);
        boolean isBuy = dataItem.getOtype().equals(BuySellEnum.BUY.getType());
        TipLevelUtil.getPingcangTip(getActivity(), isBuy, dataItem.getNewprice(), dataItem.getBuynum(), (num) -> {
            mPresenter.pingCang(num, slimAdapter.getDataItem(curPos).getHold_id() + "");

        }).show();
    }

    /**
     * 设置点位
     */
    public void setStop(WinLossBean winLossBean) {
        TradeListBean dataItem = slimAdapter.getDataItem(curPos);
        setTip = TipLevelUtil.showTradeSet(getActivity(),
                dataItem.getOtype(),
                dataItem.getNewprice(),
                winLossBean.getMin_zy(),
                winLossBean.getMax_zy(),
                winLossBean.getMin_zs(),
                winLossBean.getMax_zs(),
                list -> {
                    mPresenter.setStop(dataItem.getHold_id() + "",
                            TextUtils.isEmpty(list.get(0)) ? "0" : list.get(0),
                            TextUtils.isEmpty(list.get(1)) ? "0" : list.get(1));
                }
        );
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePrice(CoinBean stockCoinBean) {
        if (setTip != null && setTip.isShowing()) {
            if (stockCoinBean.getCode().equals(slimAdapter.getDataItem(curPos).getPname().toLowerCase())) {
                TipLevelUtil.changeTradeSet(setTip, stockCoinBean.getPrice());
            }
        }

    }

    private void startTimer() {
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> mPresenter.getTradeList());
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(subscribe);
        super.onDestroy();
    }


    public void pingCangSuccess() {
        userViewModel.update();
        refresh();
    }

}
